<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8"/>
    <meta content="width=device-width, initial-scale=1.0" name="viewport"/>
    <title>WebSocket Client</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }

        .control {
            margin-bottom: 20px;
        }

        button {
            padding: 8px 16px;
            margin-right: 10px;
            font-size: 14px;
        }

        button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        textarea {
            width: 100%;
            height: 100px;
            margin: 10px 0;
            padding: 10px;
            box-sizing: border-box;
            font-family: monospace;
        }

        #log {
            border: 1px solid #ccc;
            height: 1000px;
            overflow-y: auto;
            padding: 10px;
            background-color: #f9f9f9;
            font-family: monospace;
            white-space: pre-wrap;
        }
    </style>
</head>
<body>
<h2>数据校验平台</h2>

<div class="control">
    <button id="connectBtn">连接</button>
    <button disabled id="disconnectBtn">断开</button>
</div>

<div>
    <label for="messageInput">发送 JSON 数据：</label><br/>
    <textarea id="messageInput" placeholder='输入 JSON，例如：{"cmd": "test"}'></textarea>
</div>

<button disabled id="sendBtn">发送</button>

<h3>通信日志：</h3>
<div id="log"></div>

<script>
    let socket = null;
    const logArea = document.getElementById('log');
    const messageInput = document.getElementById('messageInput');
    const connectBtn = document.getElementById('connectBtn');
    const disconnectBtn = document.getElementById('disconnectBtn');
    const sendBtn = document.getElementById('sendBtn');

    // 日志输出函数
    function log(msg) {
        const entry = document.createElement('div');
        entry.textContent = `[${new Date().toLocaleTimeString()}] ${msg}`;
        logArea.appendChild(entry);
        logArea.scrollTop = logArea.scrollHeight; // 滚动到底部
    }

    // 更新按钮状态
    function updateButtonState(connected) {
        connectBtn.disabled = connected;
        disconnectBtn.disabled = !connected;
        sendBtn.disabled = !connected;
    }

    // 连接 WebSocket
    function connect() {
        if (socket && socket.readyState === WebSocket.OPEN) {
            log('已连接，无需重复连接');
            return;
        }

        const wsUrl = 'ws://' + window.location.host + '/ws';
        socket = new WebSocket(wsUrl);

        socket.onopen = () => {
            log('✅ 已连接到服务器');
            updateButtonState(true);
        };

        socket.onmessage = (event) => {
            log(`📩 收到消息: ${event.data}`);
        };

        socket.onclose = (event) => {
            log(`❌ 连接已关闭: ${event.code} ${event.reason}`);
            updateButtonState(false);
        };

        socket.onerror = (error) => {
            log(`❌ 连接错误: ${error.message}`);
            updateButtonState(false);
        };
    }

    // 断开连接
    function disconnect() {
        if (socket) {
            socket.close(1000, "用户手动断开");
            socket = null;
            log('手动断开连接');
            updateButtonState(false);
        }
    }

    // 发送消息
    function sendMessage() {
        const text = messageInput.value.trim();
        if (!text) {
            alert('请输入要发送的 JSON 数据');
            return;
        }

        try {
            // 验证是否为合法 JSON
            JSON.parse(text);
            socket.send(text);
            log(`📤 发送消息: ${text}`);
            messageInput.value = ''; // 清空输入框
        } catch (e) {
            alert('请输入合法的 JSON 格式');
        }
    }

    // 绑定事件
    connectBtn.addEventListener('click', connect);
    disconnectBtn.addEventListener('click', disconnect);
    sendBtn.addEventListener('click', sendMessage);

    // 页面加载时自动连接
    window.addEventListener('load', connect);
</script>
</body>
</html>
